package cn.lzd.mr.case3;

import cn.lzd.mr.PathUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * Created by lzd on 2018/6/1.
 */
public class Case3MR2 {

    static class Mp extends Mapper<LongWritable, Text, Text, Text> {

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String str = value.toString();
            String[] split = str.split("--->");
            context.write(new Text(split[0]),new Text(split[1]));
        }
    }

    static class Rd extends Reducer<Text, Text, Text, Text> {

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            String res = "";
            for (Text value : values) {
                res=res+"\t"+value;
            }

            context.write(key, new Text(res));
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration);
        job.setJarByClass(Case3MR2.class);

        job.setMapperClass(Mp.class);
        job.setReducerClass(Rd.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.setInputPaths(job,new Path(PathUtil.getpath("case3")+"out/*"));
        FileOutputFormat.setOutputPath(job,new Path(PathUtil.getpath("case3")+"out/out/"));

        System.exit(job.waitForCompletion(true)?0:1);

    }
}
